package com.lyq.demo.redis.service;

import com.lyq.demo.redis.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lyq
 * @time 2019/5/12 10:24
 */
@Service
@Slf4j
public class UserService {

    private List<User> users;

    @PostConstruct
    public void init(){
        users = new ArrayList<>();
        users.add(new User(1,"aa",18));
        users.add(new User(2,"bb",18));
        users.add(new User(3,"cc",19));
        users.add(new User(4,"dd",21));
        users.add(new User(5,"ee",18));
    }


    @Cacheable(value = "userCache",key = "#id")
    public User getById(Integer id){
        log.info("查询数据库，id={}的用户",id);
        for (User user : users) {
            if(user.getId().intValue() == id){
                return user;
            }
        }
        return null;
    }

    @CachePut(value = "userCache",key = "#id")
    public User updateById(Integer id,String name){
        log.info("更新数据库，id={}的用户",id);
        for (User user : users) {
            if(user.getId().intValue() == id){
                user.setName(name);
                return user;
            }
        }
        return null;
    }

    @CacheEvict(value = "userCache",key = "#id")
    public void deleteById(Integer id){
        log.info("删除数据库，id={}的用户",id);
        int index = -1;
        for (User user : users) {
            if(user.getId().intValue() == id){
                index = users.indexOf(user);
            }
        }
        if(index > -1){
            users.remove(index);
        }
    }
}
